package file

import (
	"bufio"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"strings"
)

// DeleteIt delete
func DeleteIt(name string) {
	err := os.RemoveAll(name)
	if err != nil {
		fmt.Printf("DeleteDir err is %v\n", err)
	}
}

// DeleteRowByKeyword delete rows by keyword
func DeleteRowByKeyword(fileName, key string) {
	f, err := os.Open(fileName)
	if err != nil {
		fmt.Printf("DeleteRowByKeyword err is %v\n", err)
	}
	reader := bufio.NewReader(f)
	var content strings.Builder
	for {
		line, err := reader.ReadString('\n')
		if err != nil {
			if err == io.EOF {
				break
			}
			fmt.Printf("DeleteRowByKeyword err is %v\n", err)
		}
		if !strings.Contains(line, key) {
			content.WriteString(line)
		}
	}
	f.Close()
	f, err = os.Create(fileName)
	if err != nil {
		fmt.Printf("DeleteRowByKeyword err is %v\n", err)
	}
	f.WriteString(content.String())
}

// DeleteKeyword delete words that appear in text
func DeleteKeyword(fileName, key string) {
	// TODO
	bytes, err := ioutil.ReadFile(fileName)
	if err != nil {
		fmt.Println(err)
	}
	content := strings.ReplaceAll(string(bytes), key, "")
	f, err := os.OpenFile(fileName, os.O_TRUNC|os.O_RDWR, os.ModePerm)
	if err != nil {
		fmt.Println(err)
	}
	defer f.Close()
	f.WriteString(content)
}
